'use client';
import PageTitle from '@/components/admin/common/PageTitle';
import Loading from '@/components/common/Loading';
import request from '@/utils/request';
import React, { useCallback, useEffect, useState } from 'react'
import message from '@/components/common/message';
import { SESSION_USERS, SESSION_ROLES } from '@/config/settings';
import Image from 'next/image';
import Popup from '@/components/admin/common/Popup';
import SuperInput from '@/components/admin/common/SuperInput';
import SuperSelect from '@/components/admin/common/SuperSelect';
import SuperPasswordInput from '@/components/admin/common/SuperPasswordInput'
import PopupHeader from '@/components/admin/common/PopupHeader';
import ImageUpload from '@/components/admin/common/ImageUpload';
import SuperChechbox from '@/components/admin/common/SuperCheckbox';
import isEqual from 'lodash/isEqual';
import Checkbox from '@/components/admin/common/Checkbox';
import {Settings, CircleUserRound} from 'lucide-react'
import IconButton from '@/components/common/IconButton';

export default function Users() {
  const [loaded, setLoaded] = useState(false);
  const [users, setUsers] = useState([]);
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [originEditingUser, setOriginEditingUser] = useState({});
  const [editingUser, setEditingUser] = useState({});
  const [roles, setRoles] = useState([]);
  const [isChange, setIsChange] = useState(false);
  const [isAddUser, setIsAddUser] = useState(false);
  const [deleteUsersList, setDeleteUsersList] = useState([]);

  useEffect(() => {
    const res = !isEqual(originEditingUser, editingUser);
    setIsChange(res);
  }, [originEditingUser, editingUser]);

  const getUsers = useCallback(() => {
    request('/api/admin/users', { method: 'GET' }).then((data) => {
      if (data.code === 0) {
        setUsers(data.data);
        sessionStorage.setItem(SESSION_USERS, JSON.stringify(data.data));
        setLoaded(true);
      } else {
        message.error(data.codeMap[data.code]);
      }
    });
  }, []);

  useEffect(() => {
    if (sessionStorage.getItem(SESSION_USERS)) {
      setUsers(JSON.parse(sessionStorage.getItem(SESSION_USERS)));
      setLoaded(true);
    } else {
      getUsers();
    }
  }, [getUsers]);

  const addEvent = () => {
    setIsAddUser(true);
    setEditingUser({avatar: '', username: '', nickname: '', password: '', role_id: 2, status: 1, email: '', phone: ''});
    setIsPopupOpen(true);
  }

  const addUserEvent = () => {
    request('/api/admin/users', { method: 'POST', credentials: 'include', body: JSON.stringify(editingUser) })
      .then((data) => {
        if (data.code === 0) {
          message.success('添加成功');
          getUsers();
          closePopup();
        } else {
          message.error(data.codeMap[data.code]);
        }
      })
  }

  const handleDeleteUsersList = (id, value) => {
    if (value) {
      setDeleteUsersList(prev => [...prev, id]);
    } else {
      setDeleteUsersList(prev => prev.filter(item => item !== id));
    }
  }

  const deleteEvent = () => {
    if (deleteUsersList.length === 0) {
      message.error('请选择要删除的用户');
      return;
    }
    request('/api/admin/users', { method: 'DELETE', credentials: 'include', body: JSON.stringify(deleteUsersList) })
      .then((data) => {
        if (data.code === 0) {
          message.success('删除成功');
          getUsers();
          setDeleteUsersList([]);
        } else {
          message.error(data.codeMap[data.code]);
        }
      })
  }

  const openPopup = (item) => {
    setIsAddUser(false);
    setOriginEditingUser({ ...item, password: '' });
    setEditingUser({ ...item, password: '' });
    setIsPopupOpen(true);
  };

  const closePopup = () => {
    setIsAddUser(false);
    setOriginEditingUser({});
    setEditingUser({});
    setIsPopupOpen(false);
  };

  const handleChange = (key, value) => {
    setEditingUser(prev => ({ ...prev, [key]: value }));
  }

  useEffect(() => {
    if (sessionStorage.getItem(SESSION_ROLES)) {
      setRoles(JSON.parse(sessionStorage.getItem(SESSION_ROLES)));
    } else {
      let rolesInfo = fetch('/api/admin/roles', { method: 'GET' });
      rolesInfo.then(res => res.json())
        .then(data => {
          if (data.code === 0) {
            setRoles(data.data);
            sessionStorage.setItem(SESSION_ROLES, JSON.stringify(data.data));
          } else {
            message.error(data.codeMap[data.code]);
          }
        })

    }
  }, []);

  const submitEvent = () => {
    if (isChange) {
      request('/api/admin/users', { method: 'PUT', credentials: 'include', body: JSON.stringify(editingUser) })
        .then((data) => {
          if (data.code === 0) {
            message.success('保存成功');
            getUsers();
            closePopup();
          } else {
            message.error(data.codeMap[data.code]);
          }
        })
    } else {
      closePopup();
    }
  }

  const resetUserInfo = () => {
    setEditingUser({ ...originEditingUser, password: '' });
  }

  const content = (
    <div>
      <Popup isOpen={isPopupOpen} onClose={closePopup}>
        <PopupHeader title={isAddUser ? '添加用户' : '编辑用户'} buttonText={isAddUser ? '添加' : (isChange ? '保存' : '关闭')} onButtonClick={isAddUser ? addUserEvent : submitEvent} extraButtonText={isAddUser ? '' : (isChange ? '重置' : '')} onExtraButtonClick={resetUserInfo} />
        <form onSubmit={e => e.preventDefault()}>
          <ImageUpload label={'头像'} state={originEditingUser?.role_id === 1 ? false : true} value={editingUser?.avatar} handleChange={(value) => handleChange('avatar', value)} className={`w-20 h-20`}/>
          <SuperInput label={'用户名'} autoComplete={'username'} state={originEditingUser?.role_id === 1 ? false : true} value={editingUser?.username} handleChange={(value) => handleChange('username', value)} />
          <SuperInput label={'昵称'} autoComplete={'nickname'} state={originEditingUser?.role_id === 1 ? false : true} value={editingUser?.nickname} handleChange={(value) => handleChange('nickname', value)} />
          <SuperInput label={'联系方式'} autoComplete={'mobile'} state={originEditingUser?.role_id === 1 ? false : true} value={editingUser?.mobile} handleChange={(value) => handleChange('mobile', value)} />
          <SuperInput label={'邮箱'} autoComplete={'email'} state={originEditingUser?.role_id === 1 ? false : true} value={editingUser?.email} handleChange={(value) => handleChange('email', value)} />
          <SuperSelect label={'角色'} state={originEditingUser?.role_id === 1 ? false : true} value={editingUser?.role_id} placeholder="选择用户角色" options={roles.map(item => ({ label: item.name, value: item.id, description: item.description }))} onChange={(value) => handleChange('role_id', Number(value))} />
          <SuperChechbox label={'状态'} state={originEditingUser?.role_id === 1 ? false : true} checked={editingUser?.status === 0 ? true : false} currentValue={editingUser?.status === 0 ? '已启用' : '已禁用'} onChange={(value) => handleChange('status', value ? 0 : 1)} />
          <SuperPasswordInput label={'密码（如果为空则不更新密码）'} autoComplete={'new-password'} state={originEditingUser?.role_id === 1 ? false : true} value={editingUser?.password} handleChange={(value) => handleChange('password', value)} />
        </form>
      </Popup>
      <PageTitle title="用户管理" buttonText={'添加'} onButtonClick={addEvent} extraButtonText={deleteUsersList.length > 0 ? '删除' : ''} onExtraButtonClick={deleteEvent} />
      <div className='flex py-3 sticky top-[48px] bg-[#FFFFFF] z-10 items-center rounded-t-xs border-b text-xs border-gray-200 text-[#333333] font-semibold px-4'>
        <div className='flex-2 flex justify-start gap-2'><span className='pl-11'>用户信息</span></div>
        <div className='flex-1 flex justify-start gap-2'>状态</div>
        <div className='flex-1 flex justify-start gap-2'>权限</div>
        <div className='flex-1 flex justify-end gap-2 pr-2'>编辑</div>
      </div>
      <div className='rounded-b-sm bg-white'>
        {
          users.length > 0 && users.map(item => (
            <div key={item.id} className='flex items-center justify-between py-2 px-4 cursor-pointer rounded-xs bg-white transition duration-100 border-b-1 border-gray-200'>
              <div className='left flex items-center gap-2 flex-2'>
                <Checkbox state={item?.role_id === 1 ? false : true} checked={deleteUsersList.includes(item.id)} onChange={(value) => handleDeleteUsersList(item.id, value)}/>
                <div className='w-10 aspect-square rounded-full overflow-hidden ml-2'>{item?.avatar ? (<Image src={item.avatar} alt="avatar" width={60} height={60} className='w-full h-full object-contain' />) : (<CircleUserRound className='w-10 h-10' color='#666'/>)}</div>
                <div className='flex flex-col gap-0.5'>
                  <h2 className='text-xs'>用户名：{item?.username}</h2>
                  <p className='text-gray-600 text-xs'>昵称：{item?.nickname}</p>
                </div>
              </div>
              <div className='flex-1 flex justify-left'>
                <p className='text-sm relative pl-3 flex items-center gap-1'>
                  {item?.status === 0 ?
                    (<><span className='absolute left-0 top-1/2 transform -translate-y-1/2 w-2 h-2 rounded-full bg-green-700'></span><span className='text-xs px-1 py-1 rounded-md'>已启用</span> </>)
                    :
                    (<><span className='absolute left-0 top-1/2 transform -translate-y-1/2 w-2 h-2 rounded-full bg-red-600'></span> <span className=' text-xs px-1 py-1 rounded-md'>未启用</span> </>)
                  }
                </p>
              </div>
              <div className='flex-1 flex justify-left'>
                <div className='text-sm'>{item?.roleInfo.code === 0 ? (<p><span className='bg-blue-800 text-white text-xs px-1.5 py-1 rounded-xs'>{item.roleInfo?.name}</span><span className='text-xs'>（{item.roleInfo?.description}）</span></p>) : <p><span className='bg-blue-500 text-white text-xs px-1.5 py-1 rounded-xs'>{item.roleInfo?.name}</span><span className='text-xs'>（{item.roleInfo?.description}）</span></p>}</div>
              </div>
              <div className='right flex-1 flex justify-end'>
                <IconButton onClick={() => openPopup(item)}><Settings color='#FFFFFF'/></IconButton>
              </div> 
            </div>
          ))
        }
      </div>
    </div>
  )

  return (
    <div>
      {loaded ? content : <Loading />}
    </div>
  )
}
